/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.vale.dao;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.apache.log4j.Logger;
import org.vale.entity.Site;

/**
 *
 * @author Gabriel Bran gbran.u@gmail.com
 */
@Stateless
public class SiteDAO extends AbstractFacade<Site, String> {
    
    @PersistenceContext(unitName = "ValeEsperarPU")
    private EntityManager entityManager;
    public static final String sqlId = "select concat('S',e.idstate,count(*)+1) from testvale.site s, testvale.city c,testvale.state e where s.idcity=c.idcity and c.idstate=e.idstate and c.idstate=?1 group by e.idstate";
    @Inject
    private transient Logger logger;
    
    public SiteDAO() {
        super(Site.class);
    }
    
    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }
    
    public String getNewSiteId(String stateId) {
        TypedQuery<String> idQuery = (TypedQuery<String>) entityManager.createNativeQuery(sqlId);
        idQuery.setParameter(1, stateId);
        try {
            String id = idQuery.getSingleResult();
            return id;
        } catch (Exception e) {
            logger.warn("Controled exception on get id for new Site", e);
            return "S" + stateId + 1;
        }
    }
    
}
